package com.joyance.springmvc.util.json;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;
import net.sf.json.util.PropertySetStrategy;
import net.sf.json.xml.XMLSerializer;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class JsonUtils {

	private static Log log = LogFactory.getLog(JsonUtils.class);

	private static ObjectMapper objectMapper = new ObjectMapper();

	public static String writeObject(Object obj) {
		if (obj == null) {
			return null;
		}
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	public static <E> E readObject(String json, Class<E> clazz) {
		if (json == null) {
			return null;
		}
		try {
			objectMapper.configure(
					JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
			objectMapper
					.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
			return objectMapper.readValue(json, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static <E> E readObject(String json, TypeReference<E> typeReference) {
		if (json == null) {
			return null;
		}
		try {
			return (E) objectMapper.readValue(json, typeReference);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 从一个JSON 对象字符格式中得到一个java对象，形如： {"id" : idValue, "name" : nameValue,
	 * "aBean" : {"aBeanId" : aBeanIdValue, ...}}
	 * 
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static Object getDTO(String jsonString, Class clazz) {
		Object obj = null;
		try {
			setDataFormat2JAVA();
			JSONObject jsonObject = null;
			jsonObject = JSONObject.fromObject(jsonString);
			obj = JSONObject.toBean(jsonObject, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}

	/**
	 * 从一个JSON 对象字符格式中得到一个java对象，形如： {"id" : idValue, "name" : nameValue,
	 * "aBean" : {"aBeanId" : aBeanIdValue, ...}}
	 * 
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static Object getDTO(JSONObject jsonObject, Class clazz) {
		Object obj = null;
		try {
			setDataFormat2JAVA();
			obj = JSONObject.toBean(jsonObject, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}

	public static Object getDTO1(String jsonStr, Class clazz) {
		Object obj = null;
		if (jsonStr != null) {
			try {
				setDataFormat2JAVA();
				JSONObject jsonObject = JSONObject.fromObject(jsonStr);
				JsonConfig jsonConfig = new JsonConfig();
				jsonConfig.setRootClass(clazz);

				Object bean = null;
				try {
					if (clazz.isInterface()) {
						if (!Map.class.isAssignableFrom(clazz)) {
							throw new JSONException(
									"beanClass is an interface. " + clazz);
						} else {
							bean = new HashMap();
						}
					} else {
						bean = jsonConfig.getNewBeanInstanceStrategy()
								.newInstance(clazz, jsonObject);
					}
				} catch (JSONException jsone) {
					throw jsone;
				} catch (Exception e) {
					throw new JSONException(e);
				}

				Map props = JSONUtils.getProperties(jsonObject);
				// 遍历
				for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries
						.hasNext();) {
					String name = (String) entries.next();
					Class type = (Class) props.get(name);

					Object value = jsonObject.get(name);

					String key = Map.class.isAssignableFrom(clazz)
							&& jsonConfig
									.isSkipJavaIdentifierTransformationInMapKeys() ? name
							: JSONUtils.convertToJavaIdentifier(name,
									jsonConfig);

					System.out.println("name=" + name + "###type=" + type
							+ "###key=" + key + "###value=" + value);

					PropertyDescriptor pd = PropertyUtils
							.getPropertyDescriptor(bean, key);
					Class targetType = pd.getPropertyType();
					System.out.println("targetType=" + targetType);

					if (!JSONUtils.isNull(value) && !value.equals("null")) {
						if (value instanceof JSONArray) {

						} else {

						}
					} else {
						if (type.isPrimitive()) {
							// assume assigned default value
							log.warn("Tried to assign null value to " + key
									+ ":" + type.getName());
							setProperty(bean, key, JSONUtils
									.getMorpherRegistry().morph(type, null),
									jsonConfig);
						} else {
							setProperty(bean, key, null, jsonConfig);
						}
					}
				}

			} catch (Exception e) {
				log.error("jsonstr转化为【" + clazz + "】报错");
			}
		}
		return obj;
	}

	private static void setProperty(Object bean, String key, Object value,
			JsonConfig jsonConfig) throws Exception {
		PropertySetStrategy propertySetStrategy = jsonConfig
				.getPropertySetStrategy() != null ? jsonConfig
				.getPropertySetStrategy() : PropertySetStrategy.DEFAULT;
		propertySetStrategy.setProperty(bean, key, value, jsonConfig);
	}

	/**
	 * 从一个JSON 对象字符格式中得到一个java对象，其中beansList是一类的集合，形如： {"id" : idValue, "name" :
	 * nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}, beansList:[{}, {},
	 * ...]}
	 * 
	 * @param jsonString
	 * @param clazz
	 * @param map
	 *            集合属性的类型 (key : 集合属性名, value : 集合属性类型class) eg: ("beansList" :
	 *            Bean.class)
	 * @return
	 */
	public static Object getDTO(String jsonString, Class clazz, Map map) {
		JSONObject jsonObject = null;
		try {
			setDataFormat2JAVA();
			jsonObject = JSONObject.fromObject(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.toBean(jsonObject, clazz, map);
	}

	/**
	 * 从一个JSON数组得到一个java对象数组，形如： [{"id" : idValue, "name" : nameValue}, {"id" :
	 * idValue, "name" : nameValue}, ...]
	 * 
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static Object[] getDTOArray(String jsonString, Class clazz) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		Object[] obj = new Object[array.size()];
		for (int i = 0; i < array.size(); i++) {
			JSONObject jsonObject = array.getJSONObject(i);
			obj[i] = JSONObject.toBean(jsonObject, clazz);
		}
		return obj;
	}

	/**
	 * 从一个JSON数组得到一个java对象数组，形如： [{"id" : idValue, "name" : nameValue}, {"id" :
	 * idValue, "name" : nameValue}, ...]
	 * 
	 * @param object
	 * @param clazz
	 * @param map
	 * @return
	 */
	public static Object[] getDTOArray(String jsonString, Class clazz, Map map) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		Object[] obj = new Object[array.size()];
		for (int i = 0; i < array.size(); i++) {
			JSONObject jsonObject = array.getJSONObject(i);
			obj[i] = JSONObject.toBean(jsonObject, clazz, map);
		}
		return obj;
	}

	/**
	 * 从一个JSON数组得到一个java对象集合
	 * 
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static List getDTOList(String jsonString, Class clazz) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		List list = new ArrayList();
		for (Iterator iter = array.iterator(); iter.hasNext();) {
			JSONObject jsonObject = (JSONObject) iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz));
		}
		return list;
	}

	/**
	 * 从一个JSON数组得到一个java对象集合，其中对象中包含有集合属性
	 * 
	 * @param object
	 * @param clazz
	 * @param map
	 *            集合属性的类型
	 * @return
	 */
	public static List getDTOList(String jsonString, Class clazz, Map map) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		List list = new ArrayList();
		for (Iterator iter = array.iterator(); iter.hasNext();) {
			JSONObject jsonObject = (JSONObject) iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz, map));
		}
		return list;
	}

	/**
	 * 从json HASH表达式中获取一个map，该map支持嵌套功能 形如：{"id" : "johncon", "name" : "小强"}
	 * 注意commons
	 * -collections版本，必须包含org.apache.commons.collections.map.MultiKeyMap
	 * 
	 * @param object
	 * @return
	 */
	public static Map getMapFromJson(String jsonString) {
		setDataFormat2JAVA();
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		Map map = new HashMap();
		for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String) iter.next();
			map.put(key, jsonObject.get(key));
		}
		return map;
	}

	/**
	 * 从json数组中得到相应java数组 json形如：["123", "456"]
	 * 
	 * @param jsonString
	 * @return
	 */
	public static Object[] getObjectArrayFromJson(String jsonString) {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		return jsonArray.toArray();
	}

	/**
	 * 把数据对象转换成json字符串 DTO对象形如：{"id" : idValue, "name" : nameValue, ...}
	 * 数组对象形如：[{}, {}, {}, ...] map对象形如：{key1 : {"id" : idValue, "name" :
	 * nameValue, ...}, key2 : {}, ...}
	 * 
	 * @param object
	 * @return
	 */
	public static String getJSONString(Object object) throws Exception {
		String jsonString = null;
		// 日期值处理器
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new JsonDateValueProcessor());
		if (object != null) {
			if (object instanceof Collection || object instanceof Object[]) {
				jsonString = JSONArray.fromObject(object, jsonConfig)
						.toString();
			} else {
				jsonString = JSONObject.fromObject(object, jsonConfig)
						.toString();
			}
		}
		return jsonString == null ? "{}" : jsonString;
	}

	private static void setDataFormat2JAVA() {
		// 设定日期转换格式
		JSONUtils.getMorpherRegistry().registerMorpher(
				new DateMorpher(new String[] { "yyyy-MM-dd",
						"yyyy-MM-dd HH:mm:ss" }));
	}

	public static Map<String, Object> parseJsonToHashMap(String jsonStr) {
		Map<String, Object> jsonInMap = null;
		try {
			jsonInMap = objectMapper.readValue(jsonStr,
					new TypeReference<Map<String, Object>>() {
					});
		} catch (Exception e) {
			log.error("parseJsonToHashMap exception, json is " + jsonStr, e);
		}
		return jsonInMap;
	}

	public static String parseXmlToJson(String xml) {
		XMLSerializer xmlSerializer = new XMLSerializer();
		JSON json = xmlSerializer.read(xml);
		String jsonStr = json.toString();
		return jsonStr;
	}

	public static Map<String, Object> parseXmlToHashMap(String xml) {
		return parseJsonToHashMap(parseXmlToJson(xml));
	}

	public static void main(String[] args) {
		String json = "{id:1,name:'gy'}";
		Map map = JsonUtils.getMapFromJson(json);
		System.out.println(map.get("name"));
	}
}
